package ar.com.jendrix.common.web;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import ar.com.jendrix.common.exception.ApplicationException;
import ar.com.jendrix.common.exception.SystemException;
import ar.com.jendrix.common.exception.ValidationException;
import ar.com.jendrix.common.persistence.entity.dto.BaseEntityDTO;
import ar.com.jendrix.common.persistence.entity.service.EntityService;

@SuppressWarnings("serial")
public abstract class EntityManagerBaseBean<DTO extends BaseEntityDTO> extends ManagerBaseBean {
	// Properties.
	private DTO entity;
	private DataModel<DTO> entityList;

	private Long entityLoadId;

	public final DTO getEntity() {
		return entity;
	}

	public final DataModel<DTO> getEntityList() {
		return entityList;
	}

	protected final void setEntityList(DataModel<DTO> entityList) {
		this.entityList = entityList;
	}

	protected abstract EntityService<DTO> getEntityService() throws SystemException;

	@Override
	protected void clear() throws ApplicationException, SystemException {
		super.clear();

		// Gets a complete list of models.
		entityList = new ListDataModel<DTO>();

		// Inits the base model.
		entity = getNewEntityDTO();
		entityLoadId = 0l;
	}

	protected abstract DTO getNewEntityDTO();

	@Override
	protected void doSearch() throws ApplicationException, SystemException {
	}

	@Override
	protected void doAdd() throws ApplicationException, SystemException {
		entity = getNewEntityDTO();
	}

	@Override
	protected void doEdit() throws ApplicationException, SystemException {
		Long entityId = entityList.getRowData().getId();
		entity = getEntityService().getFull(entityId);
	}

	@Override
	protected void doDelete() throws ApplicationException, SystemException {
		entityLoadId = entityList.getRowData().getId();
	}

	@Override
	protected void doConfirmAdd() throws ValidationException, ApplicationException, SystemException {
		getEntityService().save(getEntity());
	}

	@Override
	protected void doConfirmEdit() throws ValidationException, ApplicationException, SystemException {
		getEntityService().save(getEntity());
	}

	@Override
	protected void doSave() throws ValidationException, ApplicationException, SystemException {
		getEntityService().save(getEntity());
	}

	@Override
	protected void doConfirmDelete() throws ApplicationException, SystemException {
		getEntityService().delete(entityLoadId);
	}

	protected String getEntityDeleteMessage() {
		return "Desea eliminar el registro";
	}
}